package com.yisu.expressway.manager.website.controller.dataAnalysis;

import com.google.common.collect.Lists;
import com.yisu.expressway.ewf.common.web.JsonResult;
import com.yisu.expressway.ewf.entity.*;
import com.yisu.expressway.manager.core.service.*;
import com.yisu.expressway.manager.domain.request.GoodsCategoryRequest;
import com.yisu.expressway.manager.domain.request.GoodsSpecificationRequest;
import com.yisu.expressway.manager.domain.util.UnCompressFile;
import com.yisu.expressway.manager.domain.vo.AnalysisImageVo;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.linq4j.function.EqualityComparer;
import org.apache.calcite.linq4j.function.Function1;
import org.apache.calcite.linq4j.function.Predicate1;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.yisu.expressway.ewf.common.enums.ResponseCode.FAILURE;
import static com.yisu.expressway.ewf.common.enums.ResponseCode.SUCCESS;

/**
 * Created by xlt on 2017/5/3.
 */
@Controller
@RequestMapping(value = "/dataAnalysis")
public class DataAnalysisController {

    @Resource
    private IDataAnalysisService iDataAnalysisService;
    @Resource
    private IGoodsCategory iGoodsCategory;
    @Resource
    private IGoodsSpecificationService iGoodsSpecificationService;
    @Resource
    private IGoodsArchivesService iGoodsArchivesService;
    @Resource
    private ISpecificationGoodsService iSpecificationGoodsService;

    private List<DataAnalysisCategory> dataAnalysisCategoryList;
    private List<DataAnalusisGoods> dataAnalusisGoodsList;
    private List<AnalysisImageVo> goodsMainImages;
    private List<AnalysisImageVo> goodsDetailmages;


    private String thisPath = "";

    @RequestMapping(value = "/index.htm")
    public String shopList(Model model, HttpServletRequest request) throws Exception {
        thisPath = request.getSession().getServletContext().getRealPath("") + File.separator + "fileUpload" + File.separator;
        dataAnalysisCategoryList = iDataAnalysisService.getDataAnalysisCategoryList();
        dataAnalusisGoodsList = iDataAnalysisService.getDataAnalusisGoodsList();
        model.addAttribute("dataAnalysisCategoryList", dataAnalysisCategoryList);
        model.addAttribute("dataAnalusisGoodsList", dataAnalusisGoodsList);
        return "/dataAnalysis/index";
    }

    /**
     * 重置所有数据解析目录；
     *
     * @param model 页面传参
     * @return 页面
     */
    @RequestMapping(value = "/resetDataAnalysisJson.json")
    @ResponseBody
    public JsonResult resetDataAnalysisJson(Model model, HttpServletRequest request) {
        try {
            deleteDir(new File(thisPath));
            return new JsonResult();
        } catch (Exception ex) {
            return new JsonResult(FAILURE.code, "重置所有数据解析目录异常");
        }
    }

    private static boolean deleteDir(File dir) {
        try {
            if (dir.isDirectory()) {
                String[] children = dir.list();//递归删除目录中的子目录下
                for (int i = 0; i < children.length; i++) {
                    if (children[i].equals("长兴服务区1.zip")) {
                        int sd = 0;
                    }
                    boolean success = deleteDir(new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }
        } catch (Exception ex) {
            int i = 0;
        }
        System.gc();
        // 目录此时为空，可以删除
        return dir.delete();
    }

    /**
     * 校验类目商品数据
     *
     * @param model 页面传参
     * @return 页面
     */
    @RequestMapping(value = "/checkGoodsAnalysis.json")
    @ResponseBody
    public JsonResult checkGoodsAnalysis(Model model, HttpServletRequest request) {
        String errorInfoStr = "";
        StringBuilder errorInfoBuilder = new StringBuilder();
        try {
            if (CollectionUtils.isEmpty(dataAnalusisGoodsList)) {
                return new JsonResult(FAILURE.code, "未检测到任何商品信息");
            }
            //优先执行商品图片解压
           /* String unzipPath = thisPath + "图片.zip";
            //解压路径
            String decompressionPath = thisPath;
            UnCompressFile.unzip(unzipPath, decompressionPath);*/
            for (DataAnalusisGoods item : dataAnalusisGoodsList) {
                try {
                    Long categoryCode = getCategoryCode(item.getFirstCategory(), item.getSecondCategory(), item.getBelongCategory());
                    if (categoryCode == 0) {
                        return new JsonResult(FAILURE.code, "商品：" + item.getName() + "未检测到分类信息");
                    }
                    if(item.getName().contains("玛璐托长崎蛋糕 "))
                    {
                        int iasd=0;
                    }
                    errorInfoStr = item.getName();
                    GoodsArchives goodsArchives = new GoodsArchives();
                    SimpleDateFormat sformat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                    Long fakeGoodsNo = Long.valueOf(sformat.format(new Date()));
                    goodsArchives.setGoodsNo(fakeGoodsNo);
                    goodsArchives.setCategoryCode(String.valueOf(categoryCode));
                    goodsArchives.setName(item.getName());
                    goodsArchives.setPrivilegeDesc(item.getPrivilegeDesc());
                    goodsArchives.setBrand(item.getBrand());
                    goodsArchives.setProducingArea(item.getProducingArea());
                    goodsArchives.setTradeType(item.getTradeType());
                    goodsArchives.setTallageDesc(item.getTallageDesc());
                    goodsArchives.setTaxRateDesc("本商品的跨境综合税率为0%，不包含订单的运费和运费产生的税费");
                    goodsArchives.setStatus(1);
                    goodsArchives.setSecondName(item.getProductName());
                    goodsArchives.setProductName(item.getProductName());
                    goodsArchives.setProductCode(item.getProductCode());
                    //添加商品图片
                    goodsMainImages = Lists.newArrayList();
                    goodsDetailmages = Lists.newArrayList();
                    String mainIamgePath = thisPath + "图片" + File.separator;
                    getFileList(mainIamgePath, item.getName(), 1);
                    getFileList(mainIamgePath, item.getName(), 2);
                    if (CollectionUtils.isEmpty(goodsMainImages)) {
                        errorInfoBuilder.append("商品：" + item.getName() + "未检测到主图片信息" + "\r\n");
                    }
                    if (CollectionUtils.isEmpty(goodsDetailmages)) {
                        errorInfoBuilder.append("商品：" + item.getName() + "未检测到商品详情图信息" + "\r\n");
                    }
                    //添加规格
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    GoodsSpecificationRequest goodsSpecificationRequest = new GoodsSpecificationRequest();
                    long specificationNo = Long.valueOf(sformat.format(new Date()));
                    goodsSpecificationRequest.setSpecificationNo(specificationNo);
                    goodsSpecificationRequest.setCategoryCode(String.valueOf(categoryCode));
                    goodsSpecificationRequest.setBelongGroupName("规格");
                    goodsSpecificationRequest.setSpecificationName(item.getSpecificationName());
                    goodsSpecificationRequest.setGoodsNo(fakeGoodsNo);
                    //添加规格商品
                    SpecificationGoods specificationGoods = new SpecificationGoods();
                    specificationGoods.setBazaarPrice(item.getBazzarPrice());
                    specificationGoods.setPrice(item.getPrice());
                    specificationGoods.setGoodsNo(fakeGoodsNo);
                    specificationGoods.setCategoryCode(categoryCode);
                    specificationGoods.setSalesVolume(Double.valueOf(0));
                    specificationGoods.setSpecificationNo(specificationNo);
                    specificationGoods.setInventoryNum(item.getInventoryNum());
                } catch (Exception ex) {
                    errorInfoBuilder.append("商品名称：" + errorInfoStr + "数据校验失败：" + ex.getMessage() + "|" + ex.toString() + "\n\r");
                }
            }
        } catch (Exception ex) {
            return new JsonResult(FAILURE.code, ex.getMessage() + "");
        }
        if (!org.apache.commons.lang3.StringUtils.isEmpty(errorInfoBuilder)) {
            return new JsonResult(FAILURE.code, errorInfoBuilder + "");
        }
        return new JsonResult();
    }

    /**
     * 加载商品类目分类数据
     *
     * @param model 页面传参
     * @return 页面
     */
    @RequestMapping(value = "/resetDB.json")
    @ResponseBody
    public JsonResult resetDB(Model model, HttpServletRequest request) {
        if (iDataAnalysisService.resetGoodsInfo()) {
            return new JsonResult(SUCCESS.code, "重置数据库成功，商品档案，商品规格档案，规格商品档案已经为空！");
        } else {
            return new JsonResult(FAILURE.code, "重置数据库失败！");
        }
    }




    /**
     * 加载商品类目分类数据
     *
     * @param model 页面传参
     * @return 页面
     */
    @RequestMapping(value = "/correctImageData.json")
    @ResponseBody
    public JsonResult correctImageData(Model model) {
        List<GoodsArchives> goodsArchivesList = iGoodsArchivesService.getAllGoodsData();
        try {
            if(!CollectionUtils.isEmpty(goodsArchivesList)) {
                for (GoodsArchives item : goodsArchivesList) {
                    String iamgeStr = item.getDetailsInfo();
                    iamgeStr=iamgeStr.replace(".jpg",".jpg,");
                    iamgeStr=iamgeStr.replace(",,",",");
                    item.setDetailsInfo(iamgeStr);
                    iGoodsArchivesService.updateImageInfo(item);
                }
            }
/*
            List<String> imageColl = Lists.newArrayList();
            imageColl.add("http://oeb6w1s1c.bkt.clouddn.com/170512181455346432384048.jpg");
            imageColl.add("http://oeb6w1s1c.bkt.clouddn.com/170512143342660968867179.jpg");
            imageColl.add("http://oeb6w1s1c.bkt.clouddn.com/170512143414378825022782.jpg");
            imageColl.add("http://oeb6w1s1c.bkt.clouddn.com/170512143441742105890871.jpg");
            imageColl.add("http://oeb6w1s1c.bkt.clouddn.com/170512143510963415618563.jpg");
            String image_first = "http://oeb6w1s1c.bkt.clouddn.com/170512181455346432384048.jpg";
            String image_end = ",http://oeb6w1s1c.bkt.clouddn.com/170512143342660968867179.jpg,http://oeb6w1s1c.bkt.clouddn.com/170512143414378825022782.jpg,http://oeb6w1s1c.bkt.clouddn.com/170512143441742105890871.jpg,http://oeb6w1s1c.bkt.clouddn.com/170512143510963415618563.jpg";
            if (!CollectionUtils.isEmpty(goodsArchivesList)) {
                for (GoodsArchives item : goodsArchivesList) {
                    String detailImage = item.getDetailsInfo();
                    String[] arryImages = detailImage.split(",");
                    String images = image_first;
                    for (String ItemImage : arryImages) {
                        if(!imageColl.contains(ItemImage))
                        {
                            if (images.length() > 0) {
                                images += ",";
                            }
                            images+=ItemImage;
                        }
                    }
                    images+=image_end;
                    item.setDetailsInfo(images);
                    iGoodsArchivesService.updateImageInfo(item);
                }
            }*/
            return new JsonResult(SUCCESS.code, "重置数成功");
        }catch (Exception ex)
        {
            return new JsonResult(FAILURE.code, "重置数失败");
        }
    }





    /**
     * 加载商品类目分类数据
     *
     * @param model 页面传参
     * @return 页面
     */
    @RequestMapping(value = "/correctSpecificationName.json")
    @ResponseBody
    public JsonResult correctSpecificationName(Model model) {
        List<GoodsSpecification> goodsSpecificationList = iGoodsSpecificationService.tepmGetList();
        try {
            if (CollectionUtils.isEmpty(goodsSpecificationList)) {
                return new JsonResult(FAILURE.code, "重置数失败" + "数据获取量为0");
            }
            List<GoodsSpecification> goodsNos = Linq4j.asEnumerable(goodsSpecificationList).distinct(new EqualityComparer<GoodsSpecification>() {
                @Override
                public boolean equal(GoodsSpecification goodsSpecification, GoodsSpecification t1) {
                    return goodsSpecification.getGoodsNo().equals(t1.getGoodsNo());
                }

                @Override
                public int hashCode(GoodsSpecification goodsSpecification) {
                    return 0;
                }
            }).toList();
            List<GoodsSpecification> updateModels = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(goodsNos)) {
                for (final GoodsSpecification goodNoItem : goodsNos) {

                    List<GoodsSpecification> specifications = Linq4j.asEnumerable(goodsSpecificationList).where(new Predicate1<GoodsSpecification>() {
                        @Override
                        public boolean apply(GoodsSpecification goodsSpecification) {
                            return goodsSpecification.getGoodsNo().equals(goodNoItem.getGoodsNo());
                        }
                    }).orderBy(new Function1<GoodsSpecification, Comparable>() {
                        @Override
                        public Comparable apply(GoodsSpecification goodsSpecification) {
                            return goodsSpecification.getSpecificationNo();
                        }
                    }).toList();
                    if (CollectionUtils.isEmpty(specifications) || specifications.size() > 2) {
                        continue;
                    }
                    if (specifications.size() <= 1) {
                        continue;
                    }
                    int i = 1;
                    Long spNo = Long.valueOf(0);
                    for (GoodsSpecification specificationItem : specifications) {
                        if (spNo < specificationItem.getSpecificationNo()) {
                            GoodsSpecification updateModel = new GoodsSpecification();
                            updateModel.setSpecificationNo(specificationItem.getSpecificationNo());
                            updateModel.setBelongGroupName(specificationItem.getBelongGroupName() + i);
                            i++;
                            spNo = specificationItem.getSpecificationNo();
                            updateModels.add(updateModel);
                        }
                    }
                }
                if (!CollectionUtils.isEmpty(updateModels)) {
                    if (iGoodsSpecificationService.tempUpdateSpecificationName(updateModels)) {
                        return new JsonResult(SUCCESS.code, "操作成功");

                    } else {
                        return new JsonResult(FAILURE.code, "重置数失败");
                    }
                }
            }
            return new JsonResult(SUCCESS.code, "操作成功");
        } catch (Exception ex) {
            return new JsonResult(FAILURE.code, "重置数失败");
        }
    }


    /**
     * 加载商品数据
     *
     * @param model 页面传参
     * @return 页面
     */
    @RequestMapping(value = "/goodsAnalysis.json")
    @ResponseBody
    public JsonResult goodsAnalysis(Model model, HttpServletRequest request) {
        try {
            if (CollectionUtils.isEmpty(dataAnalusisGoodsList)) {
                return new JsonResult(FAILURE.code, "未检测到任何商品信息");
            }
          /*  //优先执行商品图片解压
            String unzipPath = thisPath + "图片.zip";
            //解压路径
            String decompressionPath = thisPath;
           UnCompressFile.unzip(unzipPath, decompressionPath);*/
            for (DataAnalusisGoods item : dataAnalusisGoodsList) {
                Long categoryCode = getCategoryCode(item.getFirstCategory(), item.getSecondCategory(), item.getBelongCategory());
                if (categoryCode == 0) {
                    return new JsonResult(FAILURE.code, "商品：" + item.getName() + "未检测到分类信息");
                }
                GoodsArchives goodsArchives = new GoodsArchives();
                SimpleDateFormat sformat = new SimpleDateFormat("yyyyMMddHHmmsss");
                Long fakeGoodsNo = Long.valueOf(sformat.format(new Date()));
                goodsArchives.setGoodsNo(fakeGoodsNo);
                goodsArchives.setCategoryCode(String.valueOf(categoryCode));
                goodsArchives.setName(item.getName());
                goodsArchives.setPrivilegeDesc(item.getPrivilegeDesc());
                goodsArchives.setBrand(item.getBrand());
                goodsArchives.setProducingArea(item.getProducingArea());
                goodsArchives.setTradeType(item.getTradeType());
                goodsArchives.setTallageDesc(item.getTallageDesc());
                goodsArchives.setTaxRateDesc("本商品的跨境综合税率为0%，不包含订单的运费和运费产生的税费");
                goodsArchives.setStatus(1);
                goodsArchives.setSecondName(item.getProductName());
                goodsArchives.setProductName(item.getProductName());
                goodsArchives.setProductCode(item.getProductCode());
                //添加商品图片
                goodsMainImages = Lists.newArrayList();
                goodsDetailmages = Lists.newArrayList();
                String mainIamgePath = thisPath + "图片" + File.separator;
                getFileList(mainIamgePath, item.getName(), 1);
                getFileList(mainIamgePath, item.getName(), 2);
                if (CollectionUtils.isEmpty(goodsMainImages)) {
                    return new JsonResult(FAILURE.code, "商品：" + item.getName() + "未检测到主图片信息");
                }
                goodsArchives.setImage(getImageUrl(goodsMainImages));
                String image_first = "http://oeb6w1s1c.bkt.clouddn.com/170512181455346432384048.jpg,";
                String image_end = ",http://oeb6w1s1c.bkt.clouddn.com/170512143342660968867179.jpg,http://oeb6w1s1c.bkt.clouddn.com/170512143414378825022782.jpg,http://oeb6w1s1c.bkt.clouddn.com/170512143441742105890871.jpg,http://oeb6w1s1c.bkt.clouddn.com/170512143510963415618563.jpg";
                String image_detail = getImageUrl(goodsDetailmages);
                if (org.apache.commons.lang3.StringUtils.isEmpty(image_detail)) {
                    continue;
                } else {
                    //goodsArchives.setDetailsInfo(image_first + image_detail + image_end);
                    goodsArchives.setDetailsInfo(image_detail);
                }
                if (org.apache.commons.lang3.StringUtils.isEmpty(goodsArchives.getImage())) {
                    return new JsonResult(FAILURE.code, "商品：" + item.getName() + "未检测到主图片信息");
                }
                if (!iGoodsArchivesService.modifyGoodsArchives(goodsArchives)) {
                    return new JsonResult(FAILURE.code, "商品：" + item.getName() + "基本信息追加失败");
                }

                //添加规格
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                GoodsSpecificationRequest goodsSpecificationRequest = new GoodsSpecificationRequest();
                long specificationNo = Long.valueOf(sformat.format(new Date()));
                goodsSpecificationRequest.setSpecificationNo(specificationNo);
                goodsSpecificationRequest.setCategoryCode(String.valueOf(categoryCode));
                goodsSpecificationRequest.setBelongGroupName("规格");
                goodsSpecificationRequest.setSpecificationName(item.getSpecificationName());
                goodsSpecificationRequest.setGoodsNo(fakeGoodsNo);
                if (!iGoodsSpecificationService.modifyGoodsSpecification(goodsSpecificationRequest)) {
                    return new JsonResult(FAILURE.code, "商品：" + item.getName() + "规格解析失败");
                }
                Thread.sleep(1000);
                if (!org.apache.commons.lang3.StringUtils.isEmpty(item.getModelType())) {
                    goodsSpecificationRequest = new GoodsSpecificationRequest();
                    specificationNo = Long.valueOf(sformat.format(new Date()));
                    goodsSpecificationRequest.setSpecificationNo(specificationNo);
                    goodsSpecificationRequest.setCategoryCode(String.valueOf(categoryCode));
                    goodsSpecificationRequest.setBelongGroupName("规格");
                    goodsSpecificationRequest.setSpecificationName(item.getModelType());
                    goodsSpecificationRequest.setGoodsNo(fakeGoodsNo);
                    if (!iGoodsSpecificationService.modifyGoodsSpecification(goodsSpecificationRequest)) {
                        return new JsonResult(FAILURE.code, "商品：" + item.getName() + "规格解析失败");
                    }
                }
                //添加规格商品
                SpecificationGoods specificationGoods = new SpecificationGoods();
                specificationGoods.setBazaarPrice(item.getBazzarPrice());
                specificationGoods.setPrice(item.getPrice());
                specificationGoods.setGoodsNo(fakeGoodsNo);
                specificationGoods.setCategoryCode(categoryCode);
                specificationGoods.setSalesVolume(Double.valueOf(0));
                specificationGoods.setSpecificationNo(specificationNo);
                specificationGoods.setInventoryNum(item.getInventoryNum());

                if (!iSpecificationGoodsService.modifySpecificationGoods(specificationGoods)) {
                    return new JsonResult(FAILURE.code, "商品：" + item.getName() + "追加失败");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new JsonResult();
    }


    /**
     * 加载商品类目分类数据
     *
     * @param model 页面传参
     * @return 页面
     */
    @RequestMapping(value = "/CategoryAnalysis.json")
    @ResponseBody
    public JsonResult CategoryAnalysis(Model model, HttpServletRequest request) {
        try {
            if (CollectionUtils.isEmpty(dataAnalysisCategoryList)) {
                return new JsonResult(FAILURE.code, "未检测到任何商品类目信息");
            }
            iGoodsCategory.resetGoodsCategory();
            for (DataAnalysisCategory item : dataAnalysisCategoryList) {
                GoodsCategory goodsCategory = new GoodsCategory();
                if (item.getParentcode().contains("0")) {
                    SimpleDateFormat sformat = new SimpleDateFormat("yyyyMMddHHmmsss");
                    String categoryCode = sformat.format(new Date());
                    goodsCategory.setCategoryCode(categoryCode);
                    goodsCategory.setParentCode(String.valueOf(0));
                    goodsCategory.setNodePath(categoryCode + ",");
                    goodsCategory.setCreateBy("sys");
                    goodsCategory.setCategoryName(item.getCategoryName());
                    goodsCategory.setDescription(item.getCategoryName());

                    Integer maxSort = iGoodsCategory.getMaxSortByParentId("0");
                    goodsCategory.setSort(maxSort + 1);
                    iGoodsCategory.modifyGoodsCategory(goodsCategory);
                    Thread.sleep(1000);
                } else {
                    GoodsCategory parModel = iGoodsCategory.getGoodsCategoryModelByName(item.getParentcode());
                    SimpleDateFormat sformat = new SimpleDateFormat("yyyyMMddHHmmsss");
                    goodsCategory.setCategoryCode(sformat.format(new Date()));
                    goodsCategory.setNodePath(parModel.getNodePath() + goodsCategory.getCategoryCode() + ",");
                    goodsCategory.setParentCode(String.valueOf(parModel.getId()));
                    goodsCategory.setCreateBy("sys");
                    goodsCategory.setCategoryName(item.getCategoryName());
                    goodsCategory.setDescription(item.getCategoryName());
                    Integer maxSort = iGoodsCategory.getMaxSortByParentId(String.valueOf(parModel.getId()));
                    goodsCategory.setSort(maxSort + 1);
                    iGoodsCategory.modifyGoodsCategory(goodsCategory);
                    Thread.sleep(1000);
                }
            }
        } catch (Exception ex) {
            return new JsonResult(FAILURE.code, "加载商品类目分类数据异常");
        }
        return new JsonResult();
    }

    /**
     * 加载商品类目分类数据
     *
     * @param model 页面传参
     * @return 页面
     */
    @RequestMapping(value = "/loadCategoryData.json")
    @ResponseBody
    public JsonResult loadCategoryData(Model model, HttpServletRequest request) {
        try {
            iDataAnalysisService.resetDataAnalysisCategory();
            iDataAnalysisService.resetDataAnalusisGoods();
            String categoryExcelPath = thisPath + "产品类目列表.xls";
            AnalysisExcel(categoryExcelPath, 1);
        } catch (Exception ex) {
            return new JsonResult(FAILURE.code, "加载商品类目分类数据异常");
        }
        return new JsonResult();
    }

    private static String errorStr = "";

    /**
     * 加载商品数据
     *
     * @param model 页面传参
     * @return 页面
     */
    @RequestMapping(value = "/loadDataForGoods.json")
    @ResponseBody
    public JsonResult loadDataForGoods(Model model, HttpServletRequest request) {
        try {
            iDataAnalysisService.resetDataAnalysisCategory();
            iDataAnalysisService.resetDataAnalusisGoods();
            String categoryExcelPath = thisPath + "产品目录.xls";
            AnalysisExcel(categoryExcelPath, 2);
        } catch (Exception ex) {
            return new JsonResult(FAILURE.code, "加载商品数据异常：" + errorStr + "|" + ex.getMessage());
        }
        return new JsonResult();
    }


    //解析excel 商家信息 dataType:1 商品类目 dataType :2 商品信息
    public void AnalysisExcel(String excelPath, Integer dataType) {
        try {
            InputStream is = null;
            Workbook wb = null;
            if (!StringUtils.isEmpty(excelPath)) {
                String filePath = excelPath;
                boolean isE2007 = false;    //判断是否是excel2007格式
                if (filePath.endsWith("xlsx"))
                    isE2007 = true;
                is = new FileInputStream(filePath);
                POIFSFileSystem poifsFileSystem = new POIFSFileSystem(is);

                wb = new HSSFWorkbook(poifsFileSystem);

                List<List<Map<String, String>>> result = new ArrayList<List<Map<String, String>>>();//对应excel文件
                int sheetSize = wb.getNumberOfSheets();
                Sheet sheet = wb.getSheetAt(0);
                List<Map<String, String>> sheetList = new ArrayList<Map<String, String>>();//对应sheet页
                List<String> titles = new ArrayList<String>();//放置所有的标题
                int rowSize = sheet.getLastRowNum() + 1;
                for (int j = 0; j < rowSize; j++) {//遍历行
                    DataAnalysisCategory dataAnalysisCategory = new DataAnalysisCategory();
                    DataAnalusisGoods dataAnalusisGoods = new DataAnalusisGoods();
                    Row row = sheet.getRow(j);
                    if (row == null) {//略过空行
                        continue;
                    }
                    int cellSize = row.getLastCellNum();//行中有多少个单元格，也就是有多少列
                    if (j == 0) {//第一行是标题行
                        for (int k = 0; k < cellSize; k++) {
                            Cell cell = row.getCell(k);
                            titles.add(cell.toString());
                        }
                    } else {
                        for (int k = 0; k < titles.size(); k++) {
                            Cell cell = row.getCell(k);
                            String key = titles.get(k).trim(); //标题
                            String value = null;
                            if (cell != null) {
                                value = cell.toString(); //对应值
                            }
                            if (dataType == 1) {
                                switch (key) {
                                    case "上级类目":
                                        dataAnalysisCategory.setParentcode(value);
                                        break;
                                    case "类目名称":
                                        dataAnalysisCategory.setCategoryName(value);
                                        break;
                                }
                            } else if (dataType == 2) {
                                switch (key) {
                                    case "一级类目":
                                        dataAnalusisGoods.setFirstCategory(value);
                                        break;
                                    case "二级类目":
                                        dataAnalusisGoods.setSecondCategory(value);
                                        break;
                                    case "所属分类":
                                        dataAnalusisGoods.setBelongCategory(value);
                                        break;
                                    case "关键词":
                                        errorStr = value;
                                        dataAnalusisGoods.setName(value);
                                        break;
                                    case "品牌":

                                        dataAnalusisGoods.setBrand(value);
                                        break;
                                    case "品名":
                                        dataAnalusisGoods.setProductName(value);
                                        break;
                                    case "驿速码":
                                        dataAnalusisGoods.setYsm(value);
                                        break;
                                    case "货品编号":
                                        dataAnalusisGoods.setProductCode(value);
                                        break;
                                    case "规格": //组名变更为规格
                                        dataAnalusisGoods.setSpecificationName(value);
                                        break;
                                    case "贸易类型": //组名变更为规格
                                        dataAnalusisGoods.setTradeType(Double.valueOf(value).intValue());
                                        break;
                                    case "库存": //组名变更为规格
                                        dataAnalusisGoods.setInventoryNum(Double.valueOf(value));
                                        break;
                                    case "型号":
                                        dataAnalusisGoods.setModelType(value);
                                        break;
                                    case "优盒价":
                                        dataAnalusisGoods.setPrice(new BigDecimal(value));
                                        break;
                                    case "市场价":
                                        dataAnalusisGoods.setBazzarPrice(new BigDecimal(value));
                                        break;
                                    case "综合税":
                                        dataAnalusisGoods.setTallageDesc(value);
                                        break;
                                    case "优惠":
                                        dataAnalusisGoods.setPrivilegeDesc(value);
                                        break;
                                    case "产地":
                                        dataAnalusisGoods.setProducingArea(value);
                                        break;
                                }
                            }
                        }
                    }
                    if (dataType == 1) {
                        if (!org.apache.commons.lang3.StringUtils.isEmpty(dataAnalysisCategory.getCategoryName())) {
                            iDataAnalysisService.addDataAnalysisCategory(dataAnalysisCategory);
                        }
                    } else if (dataType == 2) {
                        if (!org.apache.commons.lang3.StringUtils.isEmpty(dataAnalusisGoods.getName())) {
                            iDataAnalysisService.addDataAnalusisGoods(dataAnalusisGoods);
                        }
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取根级分类
     *
     * @param firstStr
     * @param secondStr
     * @param f_belong_category
     * @return
     */
    public Long getCategoryCode(String firstStr, String secondStr, String f_belong_category) {
        Long categoryCode = Long.valueOf(0);
        GoodsCategoryRequest goodsCategoryRequest = new GoodsCategoryRequest();
        GoodsCategory firstGoodsCategory = new GoodsCategory();
        GoodsCategory secondGoodsCategory = new GoodsCategory();
        GoodsCategory thirdGoodsCategory = new GoodsCategory();
        if (!org.apache.commons.lang3.StringUtils.isEmpty(firstStr)) {
            goodsCategoryRequest.setId(Long.valueOf(0));
            goodsCategoryRequest.setCategoryName(firstStr);
            firstGoodsCategory = iGoodsCategory.getGoodsCategoryModelByNameAndParentId(goodsCategoryRequest);
            if (firstGoodsCategory == null) {
                return Long.valueOf(0);
            }
            categoryCode = Long.valueOf(firstGoodsCategory.getCategoryCode());
        }
        if (!org.apache.commons.lang3.StringUtils.isEmpty(secondStr)) {
            goodsCategoryRequest.setId(firstGoodsCategory.getId());
            goodsCategoryRequest.setCategoryName(secondStr.trim());
            secondGoodsCategory = iGoodsCategory.getGoodsCategoryModelByNameAndParentId(goodsCategoryRequest);
            if (secondGoodsCategory == null) {
                return categoryCode;
            }
            categoryCode = Long.valueOf(secondGoodsCategory.getCategoryCode());
        }
        if (!org.apache.commons.lang3.StringUtils.isEmpty(f_belong_category)) {
            goodsCategoryRequest.setCategoryName(f_belong_category.trim());
            goodsCategoryRequest.setId(secondGoodsCategory.getId());
            thirdGoodsCategory = iGoodsCategory.getGoodsCategoryModelByNameAndParentId(goodsCategoryRequest);
            if (thirdGoodsCategory == null) {
                return categoryCode;
            }
            categoryCode = Long.valueOf(thirdGoodsCategory.getCategoryCode());
        }
        return categoryCode;
    }

    public String getImageUrl(List<AnalysisImageVo> images) {
        if (!CollectionUtils.isEmpty(images)) {
            List<String> ImagesArry = Lists.newArrayList();
            for (AnalysisImageVo analysisImageVo : images) {
                if (!org.apache.commons.lang3.StringUtils.isEmpty(analysisImageVo.getImagePath())) {
                    String path = iDataAnalysisService.imageUploadForAnalysis(new File(analysisImageVo.getImagePath()));
                    if (!org.apache.commons.lang3.StringUtils.isEmpty(path))
                        ImagesArry.add(path.trim());
                }
            }
            return org.apache.commons.lang3.StringUtils.join(ImagesArry, ",");
        } else {
            return "";
        }

    }

    public void getFileList(String strPath, String dirName, Integer type) {
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                if (files[i].isDirectory()) { // 判断是文件还是文件夹
                    if (fileName.contains(dirName)) {
                        String analysisImagePath = "";
                        if (type == 1) {

                            analysisImagePath = files[i].getAbsolutePath() + File.separator + "主图";
                            goodsMainImages = getFileList_ImageItems(analysisImagePath);
                        } else {
                            analysisImagePath = files[i].getAbsolutePath() + File.separator + "详情";
                            goodsDetailmages = getFileList_ImageItems(analysisImagePath);
                        }
                    }
                } else { // 判断文件名是否以.avi结尾
                    String strFileName = files[i].getAbsolutePath();
                    System.out.println("---" + strFileName);
                }
            }
        }
    }

    public List<AnalysisImageVo> getFileList_ImageItems(String strPath) {
        List<AnalysisImageVo> analysisImageVos = Lists.newArrayList();
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                if (!files[i].isDirectory()) { // 判断是文件还是文件夹
                    AnalysisImageVo analysisImageVo = new AnalysisImageVo();
                    analysisImageVo.setImagePath(files[i].getAbsolutePath().trim());
                    String fileNameWitchOutPrefix = fileName;
                    String prefix = fileNameWitchOutPrefix.substring(fileNameWitchOutPrefix.lastIndexOf("."));
                    int num = prefix.length();
                    analysisImageVo.setSort(Integer.valueOf(fileNameWitchOutPrefix.substring(0, fileNameWitchOutPrefix.length() - num)));
                    analysisImageVos.add(analysisImageVo);
                }
            }
        }
        analysisImageVos = Linq4j.asEnumerable(analysisImageVos).orderBy(new Function1<AnalysisImageVo, Comparable>() {
            @Override
            public Comparable apply(AnalysisImageVo cateVo_imageItems) {
                return cateVo_imageItems.getSort();
            }
        }).toList();
        return analysisImageVos;
    }


}

